//
//  SEGRemoteNotification.m
//  SEGStandard
//
//  Created by 山刘 on 2019/4/20.
//  Copyright © 2019年 山刘. All rights reserved.
//

#import "SEGRemoteNotification.h"

#define SEGRemoteNotificationUserDefault @"RemoteNotificationUserDefault"
#import <UserNotifications/UserNotifications.h>

#if __has_include(<Commom/SEGPlatformManager.h>)
#import <Commom/SEGPlatformManager.h>
#else
#import "SEGPlatformManager.h"
#endif

#if __has_include(<JPush/JPUSHService.h>)
#import <JPush/JPUSHService.h>
#else
#import "JPUSHService.h"
#endif


@interface SEGRemoteNotification()<JPUSHRegisterDelegate>
@end

static id _SEGRemoteNotification;
static dispatch_once_t onceToken;

@implementation SEGRemoteNotification

+(instancetype)sharedManager{
    dispatch_once(&onceToken, ^{
        _SEGRemoteNotification = [[self alloc] init];
    });
    return _SEGRemoteNotification;
}

/**
 * 初始化极光推送
 * @author Wendy
 */
- (void)initJpushWithOptions:(NSDictionary *)launchOptions
{
    //透传通知接受
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    // remotenotification,kill app
    NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        //当程序未运行时 推送至具体页面 (保存通知信息 待主界面初始化后跳转)
        [[NSUserDefaults standardUserDefaults] setObject:userInfo forKey:SEGRemoteNotificationUserDefault];
    }
    
    //极光推送新版本3.0.0 Wendy 2016-12-03
    //初始化APNs代码 notice: 3.0.0及以后版本注册可以这样写，也可以继续 旧的注册 式
    JPUSHRegisterEntity* entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert | JPAuthorizationOptionBadge | JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加 定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    //初始化JPush代码
    // notice: 2.1.5版本的SDK新增的注册 法，改成可上报IDFA，如果没有使 IDFA直接传nil
    // 如需继续使 pushConfig.plist 件声明appKey等配置内容，请依旧使 [JPUSHService setupWithOption:launchOptions] 式初始化。
    NSString *appKey;
    BOOL isProduction = [[[NSUserDefaults standardUserDefaults] valueForKey:kUserDefaultIsProduction] boolValue];
    if (isProduction) {//生产环境
        appKey = kJPUSHAppKey;
    }else {//测试环境
        appKey = kJPUSHAppTestKey;
    }
    
    [JPUSHService setupWithOption:launchOptions
                           appKey:appKey
                          channel:kJPUSHChannel
                 apsForProduction:isProduction];
    
    [JPUSHService crashLogON];//开启Crash日志收集
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    //清零推送服务器数量
    [JPUSHService resetBadge];
}

#pragma mark - 推送处理
- (void)applicationWillEnterForeground
{
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    //清零推送服务器数量
    [JPUSHService resetBadge];
    [[NSUserDefaults standardUserDefaults]setObject:@(YES) forKey:kUserDefaultApplicationEnter];
    [[NSNotificationCenter defaultCenter]postNotificationName:kApplicationEnterNotification object:nil];
}

- (void)segDidRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    NSLog(@"JPUSH_registrationID:    %@", [JPUSHService registrationID]);
}

- (void)segDidReceiveRemoteNotification:(NSDictionary*)userInfo{
    [JPUSHService handleRemoteNotification:userInfo];
    
    [self dealWithRemoteNotification:userInfo];
    
    if (@available(iOS 10.0, *)) { //iOS10以上会在didReceiveNotificationResponse处理点击通知栏的推送消息
        
    } else {
        //点击通知栏的推送消息
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive) {
            [self seg_clickNotification:userInfo];
        }
        else { //收到推送
            
        }
    }
    
}
#pragma mark - JPUSHRegisterDelegate
// iOS 10 Support 前台收到推送
- (void)jpushNotificationCenter:(UNUserNotificationCenter*)center willPresentNotification:(UNNotification*)notification withCompletionHandler:(void (^)(NSInteger))completionHandler
{
    
    NSDictionary* userInfo = notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if ([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
            [self dealWithRemoteNotification:userInfo];
        }
    } else {
        // Fallback on earlier versions
    }
    //前台收到推送也可以弹出通知栏
    //        completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support 点击通知栏调用
- (void)jpushNotificationCenter:(UNUserNotificationCenter*)center didReceiveNotificationResponse:(UNNotificationResponse*)response withCompletionHandler:(void (^)())completionHandler
{
    //Required
    NSDictionary* userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
            
            [self dealWithRemoteNotification:userInfo];
            
            [self seg_clickNotification:userInfo];
        }
    } else {
        // Fallback on earlier versions
    }
    completionHandler(); // 系统要求执行这个方法
}

#pragma mark - 统一处理推送
- (void)dealWithRemoteNotification:(NSDictionary*)userInfo
{
    NSString* serviceType = ValueToString([userInfo valueForKey:@"type"]);
    if ([serviceType isEqualToString:kMessageTypeMsmart]) {//美的SDK
        [[SEGUhomeMediator sharedInstance] seg_SmartOpenSDKDidReceiveRemoteNotification:@{@"userInfo":userInfo,@"phoneNumber":ValueToString(kAccountMobile)}];
    }else {
        //打红点
        //        [SEGAlertView showTmepMessageWithMessage:@"通知"];
        [self rodUpData:userInfo];
    }
}
// 处理点击通知栏的推送消息
- (void)seg_clickNotification:(NSDictionary*)userInfo
{
    //[SEGAlertView showTmepMessageWithMessage:@"seg_clickNotification"];
    NSDictionary *remoteNotification = [[NSUserDefaults standardUserDefaults] valueForKey:SEGRemoteNotificationUserDefault];
    if (remoteNotification) {
        return;
    }
    
    //[SEGAlertView showTmepMessageWithMessage:@"seg_clickNotification2222"];
    //推送至具体页面
    [self pushToViewControllerWithMessageInfo:userInfo];
}

#pragma mark - 接受透传通知
- (void)networkDidReceiveMessage:(NSNotification*)notification
{
    NSDictionary* userInfo = [NSDictionary new];
    if ([[[notification userInfo] allKeys] containsObject:@"extras"]) {
        userInfo = [[notification userInfo] valueForKey:@"extras"];
    }
    else {
        userInfo = [notification userInfo];
    }
    
    NSString *groupID = [userInfo valueForKey:@"groupId"];
    if (groupID && groupID.length > 0) {
        if ([groupID hasPrefix:kMessageGroupLikePre]) {//点赞消息
            [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.beLike finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            }];
        }
    }
    
    NSString* type = [userInfo objectForKey:@"type"];
    if (type && [type isKindOfClass:[NSString class]]) {
        if ([type isEqualToString:kMessageTypeWashCarPaySuccess] || [type isEqualToString:kMessageTypeWashCarPayFailed]) {//自助洗车获取设备启动状态
            // 处理自助洗车推送
            [[NSUserDefaults standardUserDefaults] setObject:type forKey:kWashCarResult];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NSNotificationWashCarResult" object:nil];
            
        } else if ([type isEqualToString:@"1"]) {//用户认证通过：1
            // 认证积分行为设置
            [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.auth finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            }];
            
        } else if ([type isEqualToString:kMessageTypeLottery]) { // 活动抽奖推送 显示抽奖气泡
            [self seg_saveLotteryCountWith:userInfo];
            return;//不进行存红点操作
            
        } else if ([type isEqualToString:@"push_type_reload"]) { // 请求极光推送TAG接口，绑定TAG
            [self requestGetPushTag];
            return;//不进行存红点操作
            
        } else if ([type isEqualToString:kMessageTypeActivityTask]) { // 透传 - 活动完成任务弹窗
            // 通知刷新 “福利社”
            [[NSNotificationCenter defaultCenter] postNotificationName:SEGRefreshActivitySignVCNotification object:nil];
            // 保存抽奖次数
            [self seg_saveLotteryCountWith:userInfo];
            // 展示活动完成弹窗
            [[SEGUhomeMediator sharedInstance] seg_showFinishActivityTaskDetailViewController:userInfo];
            return;//不进行存红点操作
        }
    }
    
    //设置红点
    //    [SEGAlertView showTmepMessageWithMessage:@"透传"];
    [self rodUpData:userInfo];
}

/// 保存抽奖次数
- (void)seg_saveLotteryCountWith:(NSDictionary *)userInfo {
    if (userInfo[@"lotteryId"] && [userInfo[@"lotteryId"] integerValue] > 0) {
        // 获取本地抽奖信息
        NSString *key = [NSString stringWithFormat:@"%@_%@",kActivityLotteryInfoArrayNew, kAccountUserID];
        NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:key];
        if(!array || array.count == 0) { // 新路径获取不到，获取老数据
            array = [[NSUserDefaults standardUserDefaults] objectForKey:kActivityLotteryInfoArray];
        }
        NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:array];
        [mutableArray addObject:userInfo];
        
        [[NSUserDefaults standardUserDefaults] setObject:mutableArray forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:SEGActivityLotteryNotification object:nil];
    }
}

#pragma mark - 设置红点
- (void)rodUpData:(NSDictionary*)userInfo
{
    //新红点逻辑
    NSString* type = ValueToString([userInfo valueForKey:@"type"]);
    
    //认证成功通知
    if ([type isEqualToString:@"1"]) {
        [[SEGProfileManager sharedManager] requestProfilecompleted:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
                //刷新用户信息
                [[NSNotificationCenter defaultCenter] postNotificationName:SEGRefreshUserInfoFinishedNotification object:nil];
            }
        }];
    }
    
    
    //物业通知控件红点
    NSArray *propertyTypes = [[SEGUhomeMediator sharedInstance] seg_getServiceTypeArray:nil];//以上类型消息得更新到首页控件：SEGEnumShowTypePropertyNotification 中。
    if ([propertyTypes containsObject:type]) {
        [[NSUserDefaults standardUserDefaults] setObject:ValueToString([userInfo valueForKey:@"title"]) forKey:SEGConstUPropertyUserDefaults];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:SEGConstUPropertyNotification object:nil userInfo:nil];
    }
    
    //物业服务工单
    if ([type isEqualToString:kMessageTypeService]) {
        //保存serviceId，用于我的服务列表打红点
        NSString* serviceId = ValueToString([userInfo valueForKey:@"serviceId"]);
        if (serviceId && serviceId.length > 0) {
            [[SEGUhomeMediator sharedInstance] seg_saveMyServiceId:@{@"serviceId":serviceId}];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:SEGConstOrderInputUserDefaults];
        }
    }
    
    [[SEGUhomeMediator sharedInstance] seg_saveRedDotWithType:@{@"type":type}];
    
    //消息红点刷新界面
    NSDictionary *dict = [[SEGUhomeMediator sharedInstance]seg_getRedDotTypeAndRescodeDict:@{}];
    
    NSString *rescode = [dict valueForKey:type];
    if (rescode && rescode.length > 0) {
        if ([rescode rangeOfString:@"RES_MESSAGE"].location != NSNotFound) {
            //消息红点
            if ([[userInfo valueForKey:@"sendUserId"] isEqualToString:kAccountUserID]) return;
            // 只有应用在前台时请求消息并刷新
            if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
                //刷新消息列表
                [[NSNotificationCenter defaultCenter] postNotificationName:@"MESSAGELISTREFRESH" object:nil];
                //私信界面即时刷新聊天内容
                [[NSNotificationCenter defaultCenter] postNotificationName:RECEIVE_MESSAGE_UI object:nil userInfo:nil];
            }
        }
    }
    //邻里圈新动态
    if([type isEqualToString:kMessageTypeNEIGHBORNEWS]) {
        // 4.9.6需求 如果邻里圈新动态是自己发的，则过滤
        if ([userInfo[@"pgcUserId"] isEqualToString:kAccountUserID]) {
            return;
        }
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:SEGNeighbourNewsUserDefaults];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:SEGNeighbourNewsNotification object:nil userInfo:nil];
    }
    
}

/**
 * 根据消息跳转到对应界面
 * @author Wendy
 */
- (void)pushToViewControllerWithRemoteNotification:(NSDictionary*)params
{
    NSDictionary *remoteNotification = [[NSUserDefaults standardUserDefaults] valueForKey:SEGRemoteNotificationUserDefault];
    if (remoteNotification) {
        NSDictionary *userInfo = remoteNotification;
        [self pushToViewControllerWithMessageInfo:userInfo];
        [[NSUserDefaults standardUserDefaults] setValue:nil forKey:SEGRemoteNotificationUserDefault];//清空远程通知
    }
}

- (void)pushToViewControllerWithMessageInfo:(NSDictionary*)userInfo
{
    NSString* type = [userInfo objectForKey:@"type"];
    NSString* serviceId = [userInfo objectForKey:@"serviceId"];
    
    // 删除红点逻辑
    if (type) {
        [[SEGUhomeMediator sharedInstance] seg_deleteRedDotWithType:@{@"type":type}];
    }
    
    //物业服务工单
    if ([type isEqualToString:kMessageTypeService]) {
        NSString* serviceId = ValueToString([userInfo valueForKey:@"serviceId"]);
        if (serviceId && serviceId.length > 0) {
            //删除我的服务列表对应的红点
            [[SEGUhomeMediator sharedInstance] seg_deleteMyServiceId:@{@"serviceId":serviceId}];
            //删除物业服务红点
            [[SEGUhomeMediator sharedInstance] seg_deleteRedDotWithType:@{@"type" : kMessageTypeService}];
            // 删除工单入口红点
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:SEGConstOrderInputUserDefaults];
        }
    }
    
    
    UIViewController* curentVC = [[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil];
    
    NSArray *propertyTypes = [[SEGUhomeMediator sharedInstance] seg_getServiceTypeArray:nil];
    if ([propertyTypes containsObject:type]) {
        //跳转到物业服务列表界面
        NSDictionary *tmp = (NSDictionary*)[[NSUserDefaults standardUserDefaults]objectForKey:SEGUPropertyNotificationUserDefaults];
        if (tmp && [tmp isKindOfClass:[NSDictionary class]]) {
            UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initServiceMessageViewController:@{@"serviceBaseInfoModel":tmp}];
            vc.hidesBottomBarWhenPushed = YES;
            [curentVC.navigationController pushViewController:vc animated:YES];
        }
        //删除物业通知控件红点
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:SEGConstUPropertyUserDefaults];
        [[NSNotificationCenter defaultCenter] postNotificationName:SEGConstUPropertyNotification object:nil userInfo:nil];
        return;
    }
    
    NSDictionary *dict = [[SEGUhomeMediator sharedInstance]seg_getRedDotTypeAndRescodeDict:@{}];
    
    NSString *rescode = [dict valueForKey:type];
    if (rescode && rescode.length > 0) {
        if ([rescode rangeOfString:@"RES_MESSAGE"].location != NSNotFound) { //消息推送
            //自助洗车点击推送的通知
            if ([type isEqualToString:kMessageTypeWashCarPaySuccess] || [type isEqualToString:kMessageTypeWashCarPayFailed]) {
                //跳转到自助洗车界面
                UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initWashCarViewController:nil];
                vc.hidesBottomBarWhenPushed = YES;
                [curentVC.navigationController pushViewController:vc animated:YES];
            } else {  // 跳转到消息列表（注意项目的消息列表是tab还是右上角的入口）
                [[SEGUhomeMediator sharedInstance] seg_autoSelctedToTabWithAction:@"TAB_MESSAGE"];
            }
            return;
        }
    }
    
    if ([type isEqualToString:@"100210"]) { //我的活动
        NSDictionary *params = @{@"serviceId":serviceId};
        UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initOtherCreateActivityDetailViewController:params];
        vc.hidesBottomBarWhenPushed = YES;
        [curentVC.navigationController pushViewController:vc animated:YES];
        
    } else if ([type isEqualToString:@"101100"]) {
        UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initMonthCardCheckViewController:nil];
        vc.hidesBottomBarWhenPushed = YES;
        [curentVC.navigationController pushViewController:vc animated:YES];
        
    } else if ([type isEqualToString:@"C_PUSH_QCH_NOTICE"]) {//侨城汇
        NSString *str = [userInfo objectForKey:@"url"];
        NSString* urlStr = [NSString stringWithFormat:@"%@?parms={\"userId\":\"segi_userid\", \"communityId\":\"segi_cid\",\"houseId\": \"segi_houseId\",\"tel\":\"segi_tel\", \"nickname\": \"segi_nickname\"}",str];
        NSDictionary *params = @{@"linkURL":urlStr};
        UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initWebViewLoadController:params];
        vc.hidesBottomBarWhenPushed = YES;
        [curentVC.navigationController pushViewController:vc animated:YES];
        
    } else if ([type isEqualToString:@"C_PUSH_TYPE_BUSI"]) {
        NSString *str = [userInfo objectForKey:@"url"];
        NSString* urlStr = [NSString stringWithFormat:@"%@%@",kClientRootURL,str];
        NSDictionary *params = @{@"linkURL":urlStr};
        UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initWebViewLoadController:params];
        vc.hidesBottomBarWhenPushed = YES;
        vc.title = [userInfo objectForKey:@"title"];
        [curentVC.navigationController pushViewController:vc animated:YES];
        
    } else if ([type isEqualToString:kMessageTypeNotice]) { // 处理外部链接
        NSDictionary *params = @{@"linkURL": [userInfo objectForKey:@"url"]};
        UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initWebViewLoadController:params];
        [curentVC.navigationController pushViewController:vc animated:YES];
        
    }
}

/**
 * 提交极光推送token
 * @author Wendy
 */
- (void)seg_submitJpushToken:(NSDictionary*)params
{
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString* registrationID) {
        if (registrationID && registrationID.length > 0) {
            
            [self requestSubmitToken:registrationID Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                [self seg_requestSignUpIntegralGrowth];
                [self seg_requestLoginIntegralGrowth];
                [self seg_requestUpdateProductIntegralGrowth];
            }];
        }
        else {
            [self seg_requestSignUpIntegralGrowth];
            [self seg_requestLoginIntegralGrowth]; 
            [self seg_requestUpdateProductIntegralGrowth];
        }
    }];
}

/**
 用户注册积分成长值
 */
- (void)seg_requestSignUpIntegralGrowth
{
    NSString *key = [NSString stringWithFormat:@"%@_%@",kSubmitTokenIsNewUserRegisterKey,kAccountUserID];//区分用户，解决注册之后没有登录成功，切换其他账号，其他账号请求注册行为的问题
    NSString *isNewUserRegister = [[NSUserDefaults standardUserDefaults] stringForKey:key];
    if (isNewUserRegister && [isNewUserRegister isEqualToString:@"1"]) {
        //注册成功后先提交极光registrationID 再请求积分增长接口 这样才能收到注册成功的消息透传
        //注册新用户积分成长值
        [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.signup finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
                [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:key];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }];
    }
}

/// 用户登录积分成长值
- (void)seg_requestLoginIntegralGrowth
{
    NSString *key = [NSString stringWithFormat:@"%@_%@",kSubmitTokenIsLoginKey,kAccountUserID];//区分用户
    NSString *isNewUserRegister = [[NSUserDefaults standardUserDefaults] stringForKey:key];
    if (isNewUserRegister && [isNewUserRegister isEqualToString:@"1"]) {
        [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.login finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
                [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:key];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }];
    }
}

/// 用户更新产品积分成长值
- (void)seg_requestUpdateProductIntegralGrowth
{
    NSString *versionString = [[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultLastVersionCode];
    BOOL shouldRequst = NO;
    if (!versionString) {//之前没有保存过-- 第一次安装
        shouldRequst = YES;
    }
    if (versionString && [versionString integerValue] < [[SEGServerManager getClientVersionCode] integerValue]) { //从老版本升级上来
        shouldRequst = YES;
    }
    if (shouldRequst) {
        ///请求更新产品行为设置接口
        [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.updateProduct finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        }];
        [[NSUserDefaults standardUserDefaults] setObject:[SEGServerManager getClientVersionCode] forKey:kUserDefaultLastVersionCode];
    }
}

#pragma mark - 极光推送
/**
 * 提交极光推送的Token
 * @author Wendy
 * @param token 极光推送的token
 */
- (void)requestSubmitToken:(NSString*)token Finished:(SEGNetworkReponse)finished
{
    NSDictionary* params = @{
                             @"isOpen" : @"1",
                             @"userId": kAccountUserID,
                             @"tokenCode": token,
                             @"extend1" : @"IOS"
                             };
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/user/submitToken",nil];
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        finished(isSuccessed, result, codeType, errorMessage);
    }];
}

/**
 * 获取极光推送要设置的tag
 * @author Wendy
 */
- (void)requestGetPushTag
{
    NSDictionary* params = @{
                             @"communityId" : kAccountCommunityID
                             };
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/bms-api/bms/message/api/getCTags",nil];
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        //设置极光推送的tag
        NSDictionary *data = [result valueForKey:@"data"];
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSArray *tags = [data valueForKey:@"tags"];
            if (tags && [tags isKindOfClass:[NSArray class]] && tags.count > 0) {
                //保存tags到本地
                NSMutableDictionary *allDict = [NSMutableDictionary dictionary];
                NSDictionary *tempDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:kJPUSHTagsKey];
                if (tempDict) {
                    [allDict addEntriesFromDictionary:tempDict];
                }
                NSString *currentUserAndCommunity = [NSString stringWithFormat:@"%@,%@", kAccountUserID, kAccountCommunityID];
                [allDict setValue:tags forKey:currentUserAndCommunity];
                [[NSUserDefaults standardUserDefaults] setObject:allDict forKey:kJPUSHTagsKey];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }
        
        [self setJPushTags];
    }];
    
}

- (void)setJPushTags
{
    //推送设置
    NSSet* tag;
    //先获取本地tag
    NSDictionary *allDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:kJPUSHTagsKey];
    if (allDict && [allDict isKindOfClass:[NSDictionary class]]) {
        NSString *currentUserAndCommunity = [NSString stringWithFormat:@"%@,%@", kAccountUserID, kAccountCommunityID];
        NSArray *tagsArray = [allDict valueForKey:currentUserAndCommunity];
        if (tagsArray && [tagsArray isKindOfClass:[NSArray class]] && tagsArray.count > 0) {
            tag = [NSSet setWithArray:tagsArray];
        }
    }
    
    if (!tag) {
        SEGProfileModel *account = [SEGProfileManager sharedManager].profile;
        tag = [NSSet setWithObjects:
               [NSString stringWithFormat:@"UHOME%@", kAccountCommunityID == nil ? @"" : kAccountCommunityID],
               [NSString stringWithFormat:@"RADIOCITY%@", account.cityId == nil ? @"" : account.cityId],
               [NSString stringWithFormat:@"RADIOCOMMUNITY%@",  kAccountCommunityID == nil ? @"" : kAccountCommunityID],
               @"RADIOALL",
               [NSString stringWithFormat:@"RADIORADIOPRO%@", account.province == nil ? @"" : account.province],
               nil];
    }
    /*
     参数说明
     tags
     不能设置nil或者空集合（[NSSet set]）
     集合成员类型要求为NSString类型
     每次调用至少设置一个 tag
     有效的标签组成：字母（区分大小写）、数字、下划线、汉字、特殊字符@!#$&*+=.|
     限制：每个 tag 命名长度限制为 40 字节，最多支持设置 1000 个 tag，但总长度不得超过5K字节。（判断长度需采用UTF-8编码）
     单个设备最多支持设置 1000 个 tag。App 全局 tag 数量无限制
     
     completion
     用于回调返回对应的参数tags。并返回对应的状态码：0为成功，其他返回码请参考错误码定义。seq为调用时传入的会话序列号
     
     seq
     请求时传入的序列号，会在回调时原样返回
     */
    [JPUSHService setTags:tag completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
    } seq:0];
}
@end
